<?php 
class IndexController extends Controller
{
	private static $pdo = null;
	/**
	 * 构造方法
	 */
	 public function __construct()
	 {
	 	//链接数据库
	 	if(is_null(self::$pdo))
		{
			try{
			    //链接数据库
			 	self::$pdo = new Pdo("mysql:host=127.0.0.1;dbname=data","root","");
				//设置字符集
				self::$pdo->query("set names utf8");
				//设置错误属性
				self::$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
							    
			}catch(PDOException $e){
			     die($e->getMessage());
			}
		}
	 	
	 }
	/**
	 * 载入首页
	 */
	public function index()
	{
		include './tpl/index.php';
	}
	/**
	 * 注册页面
	 */
	 public function register()
	 {
	 	if(IS_POST)
	 	{
	 		try{
	 		    $username=$_POST['username'];
				$password=md5($_POST['password']);
				//检测用户是否已存在
				$result = self::$pdo->query("select * from admin where  username = {$username}");
				//接收结果集
				$res = $result->fetchAll(PDO::FETCH_ASSOC);
				if(!empty($res))
				{
					$this->error("用户名已存在");
				
				}
				//预准备
				$sql = 'insert into admin (username,password) values (?,?)';
				$state = self::$pdo->prepare($sql);
				$username = $_POST['username'];
				$password = md5($_POST['password']);
				//绑定参数
				$state->bindParam(1,$username,PDO::PARAM_STR);
				$state->bindParam(2,$password,PDO::PARAM_STR);
				//执行
				$rows=$state->execute();
				if($rows)
				{
					$this->success('注册成功','./index.php?a=login');
				}else{
					$this->error('注册失败');
				}
					 		    
	 		}catch(PDOException $e){
	 		      echo $e->getMessage();
	 		}
	 	}
		include './tpl/register.php';
	 }
	 /**
	  * 登录
	  */
	 public function login()
	 {
	 	if(IS_POST)
		{
			try{
			    $username = $_POST['username'];
				$password = md5($_POST['password']);
				//预准备
				$state = self::$pdo->prepare("select * from admin where username=? and password=?");
				//绑定参数
				$state->bindParam(1,$username,PDO::PARAM_STR);
				$state->bindParam(2,$password,PDO::PARAM_STR);
				//执行
				$state->execute();
				//接收
				$rows = $state->fetchAll(PDO::FETCH_ASSOC);
				if(!empty($rows))
				{
					
					//用户名存入
					$_SESSION['username']=$username;
					//成功提示
					$this->success('登录成功', './index.php');
				}else{
					
					$this->error("登陆失败");
				}				
			    
			}catch(PDOException $e){
			     die($e->getMessage());
			}
						
		}
		include './tpl/login.php';
	 }
}


